package com.netty.esc.service.http.impl;

import com.netty.esc.Interceptor.annotation.FuckAll;
import com.netty.esc.common.base.HttpStatusCodeEM;
import com.netty.esc.common.base.BaseResponseDTO;
import com.netty.esc.dao.mapper.UserMapper;
import com.netty.esc.dao.repository.UserRepository;
import com.netty.esc.entity.model.UserInfoDTO;
import com.netty.esc.entity.pojo.UserInfo;
import com.netty.esc.service.http.UserService;
import com.netty.esc.utils.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@FuckAll
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;

    @Resource
    TokenUtil tokenUtil;

    @Resource
    UserRepository userRepository;

    @Value("${user.header}")
    String header;

    private static String NAME_HEAD = "esc-im:";

    @Override
    public UserInfo getUserLoginMessage(UserInfoDTO userInfoDTO) {
        return userMapper.getUserLoginMessage(userInfoDTO.getTelephone(), userInfoDTO.getPassword());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponseDTO<?> userSign(UserInfoDTO userInfoDTO) {
        String name = userInfoDTO.getName();
        String head = userInfoDTO.getHead();
        if (StringUtils.isEmpty(head)){
            userInfoDTO.setHead(header);
        }
        if (StringUtils.isEmpty(name)){
            userInfoDTO.setName(NAME_HEAD+userInfoDTO.getTelephone());
        }
        userInfoDTO.setCreateTime(new Date());
        userInfoDTO.setIsDel(0);
        //验证手机号是否被注册
        UserInfo userInfoByTelephone = userMapper.getUserInfoByTelephone(userInfoDTO.getTelephone());
        if (userInfoByTelephone!=null){
            return BaseResponseDTO.setResultError(HttpStatusCodeEM.USER_IS_LOGIN,"手机号已被注册");
        }
        Long i = userMapper.userSign(userInfoDTO);
        if (i<=0){
            return BaseResponseDTO.setResultError("注册失败");
        }
        String token = tokenUtil.makeTokenInRedis(userInfoDTO);
        Object node = userRepository.createNode(userInfoDTO.getId());
        //token写入redis成功
        if (!StringUtils.isBlank(token)){
            Map<String,String> map = new HashMap<>();
            map.put("token",token);
            return BaseResponseDTO.setResultSuccess(map);
        }else {
            throw new RuntimeException("token生成或者写入失败...请稍后重试");
        }
    }



}
